package com.zhong.scanerdemo.network;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import com.zhong.scanerdemo.utils.ClientLogUtil;
import com.zhong.scanerdemo.utils.KeyAndUrl;


public class ByPost {
	private final String TAG = "ByPost";
	private  final int CONNECTION_TIMEOUT = 5000;
	private  final int SOCKET_TIMEOUT = 8000;

	public ByPost() {
		super();
	}

	public String request(List<NameValuePair> nameValuePairs, String url) {
		HttpClient httpClient = getHttpClient();
		HttpPost httpPost = new HttpPost(url);
		try {
			HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
					nameValuePairs, KeyAndUrl.HTTP_ENCODE);
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
//			HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
//					nameValuePairs);
			httpPost.setEntity(requestHttpEntity);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			ClientLogUtil.i(TAG, "after  execute");
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				ClientLogUtil.i(TAG, httpResponse.getStatusLine().toString());
				String strResult = EntityUtils.toString(httpResponse
						.getEntity());
				ClientLogUtil.i(TAG, "获取数据成功");
				return strResult;
			} 
		} 
		catch (Exception e) {
			e.printStackTrace();
			ClientLogUtil.i(TAG, "Exception");
			return null;
		}
		return null;
	}

	private HttpClient getHttpClient() {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);
		HttpClient httpClient = new DefaultHttpClient(httpParams);
		return httpClient;
	}
}
